const cloud = require('wx-server-sdk')

cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  const {OPENID} = cloud.getWXContext()
  const {sold} = event
  const db = cloud.database()
  const _ = db.command
  // 数据处理
  const _soldArray = sold.map(item => {
    // 更新销量
    db.collection('goods')
    .where({
      _id: item._id
    })
    .update({
      data: {
        sales: _.inc(item.number),
        updateTime: new Date()
      }
    })
    return {
      creationTime: new Date(),
      goodsId: item._id,
      number: item.number,
      openId: OPENID,
      updateTime: new Date()
    }
  })
  
  const data = await cloud.database().collection('sold')
  .add({
    data: _soldArray
  })
  .then((e) => {
    const {errMsg} = e
    if (errMsg == 'collection.add:ok') return {
      code: 200,
      msg: '成功'
    }
    else return {
      code: 400,
      msg: '失败'
    }
  })
  .catch(() => ({
    code: 400,
    msg: '失败'
  }))
  return data
}
